package com.idopartx.phonelightning.service

import android.app.Service
import android.content.Context
import android.content.Intent
import android.hardware.Camera
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.IBinder
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import com.idopartx.phonelightning.common.Constant
import com.idopartx.phonelightning.entity.CallLightningEntity
import com.idopartx.phonelightning.entity.ScreenLightningEntity
import com.idopartx.phonelightning.utils.WindowsUtils
import com.tencent.mmkv.MMKV


class TelListenerService : Service() {
    // 电话管理器
    private var telephonyManager: TelephonyManager? = null

    // 监听器对象
    private var listener: PhoneListener? = null
    private var lighting = false
    private var camera: Camera? = null
    private var isStart: Boolean = false
    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    /**
     * 服务创建的时候调用的方法
     */
    override fun onCreate() {
        // 后台监听电话的呼叫状态。
        // 得到电话管理器
//        LogUtils.e("创建监听电话服务!")
        telephonyManager = this.getSystemService(TELEPHONY_SERVICE) as TelephonyManager
        listener = PhoneListener()
        telephonyManager?.listen(listener, PhoneStateListener.LISTEN_CALL_STATE)
        super.onCreate()
    }


    private inner class PhoneListener : PhoneStateListener() {
        // 当电话的呼叫状态发生变化的时候调用的方法
        override fun onCallStateChanged(state: Int, incomingNumber: String) {
            super.onCallStateChanged(state, incomingNumber)
            try {

                when (state) {
                    TelephonyManager.CALL_STATE_IDLE -> if (lighting) {
                        WindowsUtils.hidePopupWindow()
                        //关闭闪光灯
                        closeStar()
                    }
                    TelephonyManager.CALL_STATE_RINGING -> {
                        val screenCache = MMKV.defaultMMKV().decodeParcelable(
                            Constant.MMKV_SAVE_SCREEN_LIGHTNING,
                            ScreenLightningEntity::class.java
                        )

                        if (screenCache != null) {
                            WindowsUtils.showPopupWindow(applicationContext, screenCache)
                        }
                        //这里开启闪光灯
                        lighting = true
                        openStar()
                    }
                    TelephonyManager.CALL_STATE_OFFHOOK -> if (lighting) {
                        WindowsUtils.hidePopupWindow()
                        //关闭闪光灯
                        closeStar()
                    }
                    else -> {
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 开启闪烁
     */
    fun openStar() {
        isStart = true
        val entity = MMKV.defaultMMKV()
            .decodeParcelable(Constant.SAVE_CURRENT_LIGHTNING, CallLightningEntity::class.java)
            ?: return

        val lightNightList = entity?.lightNightList ?: arrayListOf()

        Thread {
            while (isStart) {
                lightNightList.forEach {
                    if (!isStart) return@forEach
                    open()
                    try {
                        Thread.sleep(it.light.toLong())
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                    close()
                    try {
                        Thread.sleep(it.night.toLong())
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }

                }
            }
        }.start()
    }

    /**
     * 关闭闪烁
     */
    fun closeStar() {
        isStart = false
    }

    /**
     * 打开闪光灯
     *
     * @return
     */
    private fun open() {
        try {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                val camManager =
                    applicationContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager

                val cameraId = camManager.cameraIdList[0]

                camManager.setTorchMode(cameraId, true)
            } else {
                camera = Camera.open()
                camera?.startPreview()
                val parameters = camera?.parameters
                parameters?.flashMode = Camera.Parameters.FLASH_MODE_TORCH
                camera?.parameters = parameters
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 关闭闪光灯
     *
     * @return
     */
    private fun close() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                val camManager =
                    applicationContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager

                val cameraId = camManager.cameraIdList[0]

                camManager.setTorchMode(cameraId, false)
            } else {
                val parameters = camera?.parameters
                parameters?.flashMode = Camera.Parameters.FLASH_MODE_OFF
                camera?.parameters = parameters
                camera?.release()
                camera = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 服务销毁的时候调用的方法
     * 保护监听服务
     */
    override fun onDestroy() {
        super.onDestroy()
        // 取消电话的监听,采取线程守护的方法，当一个服务关闭后，开启另外一个服务，除非你很快把两个服务同时关闭才能完成
        val i = Intent(this, TelProtectService::class.java)
        startService(i)
        listener = null
    }
}